package netty02;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDate;

public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
        String content = msg.text();
        System.out.println("接收的数据：" + content);

        String message = "服务器在[" + LocalDate.now() + "],接收到的消息：[" + content + "]";
        System.out.println("接收的数据：" + message);
        clients.writeAndFlush(new TextWebSocketFrame(message));

//        for (Channel channel : clients) {
//            channel.writeAndFlush(new TextWebSocketFrame(message));
//        }

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        clients.remove(ctx.channel());
        System.out.println("客户端断开，id=" + ctx.channel().id()
                + "，短id=" + ctx.channel().id().asShortText()
                + "，长id=" + ctx.channel().id().asLongText());
    }
}
